import React, { useState, useEffect } from 'react';
import {
  Card,
  Select,
  Input,
  Button,
  Table,
  message
} from 'antd';
import { PlusOutlined } from '@ant-design/icons'; // 导入具体图标
import LinkButton from '../../components/link-button';
import { reqProducts, reqSearchProducts, reqUpdateProductStatus } from '../../api';
import { PAGE_SIZE } from '../../utils/constants';
import { useNavigate } from 'react-router-dom';

const Option = Select.Option;

const ProductHome = () => {
  const [total, setTotal] = useState(0);// 总商品数（用于分页）
  const [products, setProducts] = useState([]); // 商品列表数据
  const [searchType, setSearchType] = useState('productName');// 搜索类型（名称/描述）
  const [searchName, setSearchName] = useState('');//搜索关键字
  const [pageNum, setPageNum] = useState(1); // 当前页码
  const navigate = useNavigate();

  //更新商品状态
  const updateProductStatus = async (productId, status) => {
    const result = await reqUpdateProductStatus(productId, status);  // 调用后台接口
    if (result.status === 0) {
      message.success('更新状态成功!');
      getProducts(pageNum);
    }
  };

  const initColumns = () => {
    return [
      {
        title: '商品名称',
        dataIndex: 'name'
      },
      {
        title: '商品描述',
        dataIndex: 'desc'
      },
      {
        title: '价格',
        dataIndex: 'price',
        render: (price) => <span>¥{price}</span>
      },
      {
        title: '状态',
        width: 100,
        dataIndex: 'status',
        render: (status, product) => {
          let btnText = '下架';
          let statusText = '在售';
          if (status === 2) {
            btnText = '上架';
            statusText = '已下架';
          }
          status = status === 1 ? 2 : 1; //切换状态（1→2，2→1）
          return (
            <span>
              <Button type='primary' onClick={() => updateProductStatus(product._id, status)}>
                {btnText}
              </Button>
              <span>{statusText}</span>
            </span>
          );
        }
      },
      {
        title: '操作',
        width: 100,
        render: (product) => (
          <span>
            <LinkButton onClick={() => navigate('detail', { state: product })}>
              详情
            </LinkButton>
            <LinkButton onClick={() => navigate('addupdate', { state: product })}>
              修改
            </LinkButton>
          </span>
        )
      }
    ];
  };

  //获取指定页码
  const getProducts = async (page) => {
    setPageNum(page);  // 更新当前页码（用于分页）
    let result;
    if (searchName) { // 有搜索关键字时调用搜索接口
      result = await reqSearchProducts({
        pageNum: page,
        pageSize: PAGE_SIZE,
        searchType,
        searchName
      });
    } else {   // 无搜索时调用普通获取接口
      result = await reqProducts(page, PAGE_SIZE);
    }
    console.log('getProducts()', result);
    if (result.status === 0) {
      const { total, list } = result.data; // 解构总数量和商品列表
      setTotal(total);// 更新总商品数
      setProducts(list);// 更新商品列表
    }
  };

  useEffect(() => {
    getProducts(1); // 组件挂载时，获取第 1 页数据
  }, []);// 依赖项为空，仅在组件首次渲染后执行

  const columns = initColumns();

  const title = (
    <span>
      <Select value={searchType} onChange={(value) => setSearchType(value)}>
        <Option key='productName' value='productName'>按名称搜索</Option>
        <Option key='productDesc' value='productDesc'>按描述搜索</Option>
      </Select>
      <Input
        style={{ width: 150, marginLeft: 10, marginRight: 10 }}
        placeholder=' 关键字'
        onChange={(e) => setSearchName(e.target.value)}
      />
      <Button type='primary' onClick={() => getProducts(1)}>搜索</Button>
    </span>
  );

  const extra = (
    <Button
      type='primary'
      style={{ float: 'right' }}
      onClick={() => navigate('/admin/products/addupdate')}
    >
      <PlusOutlined /> {/* 图标组件 */}
      添加商品
    </Button>
  );

  return (
    <div>
      <Card title={title} extra={extra}>
        <Table
          bordered
          rowKey='_id'
          columns={columns}
          dataSource={products}
          pagination={{
            defaultPageSize: PAGE_SIZE,
            total,
            showQuickJumper: true,
            onChange: getProducts
          }}
        />
      </Card>
    </div>
  );
};

export default ProductHome;